#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import <sqlite3.h>
#import <UIKit/UIApplication.h>
#import "../LockInfo/Plugin.h"

#import "framework/FWCommon.h"

#import "PICommon.h"
#import "PIPlugin.h"
#import "PIContextList.h"
#import "PIListAccess.h"
#import "PIIntegration.h"
#import "PIStatus.h"


@implementation PIContextList

@synthesize selected;


// ******************************************************************************************
#pragma mark -
#pragma mark Initialisation and object management

- (void) dealloc
{
    [selected release];
    
    [super dealloc];
}


// ******************************************************************************************
#pragma mark -
#pragma mark Handling user input

- (BOOL)cancelClicked:(FWApplication*)application sections:(NSArray*)sections
{
    return YES;
}

- (BOOL)selectClicked:(FWApplication*)application sections:(NSArray*)sections
{
    [application setAttribute:kPIApplicationContextCurrent value:self.selected];
    
    ((PIStatus*)application.info).autoContextOn = YES;
    ((PIStatus*)application.info).fixedContextOn = NO;
    
    [((PIPlugin*)application.plugin) triggerUnconditionalRefresh];
    
    return YES;
}


// ******************************************************************************************
#pragma mark -
#pragma mark Accessing records from the database

- (NSArray*)dataForIndex:(NSInteger)i list:(NSArray*)list database:(NSString*)dbpath application:(FWApplication*)application
{  
    self.selected = [PIIntegration locationContextsFromPI];
    
    NSString *sql = @"select id, name, icon from context order by name";
    NSArray* record = FWDBGetRecords(sql, 1, dbpath, application, self);
    
    return [NSArray arrayWithObjects:record, nil];
}

- (NSObject*)objectForSQLRecord:(sqlite3_stmt*)sqlStatement withId:(NSInteger)sqlid application:(FWApplication*)application
{
    int cId = sqlite3_column_double(sqlStatement, 0);
    const char *cTitle = (const char*)sqlite3_column_text(sqlStatement, 1);
    const char *cIcon = (const char*)sqlite3_column_text(sqlStatement, 2);
    
    NSString* title = [NSString stringWithUTF8String:(cTitle == NULL ? "" : cTitle)];
    NSString* icon = [NSString stringWithUTF8String:(cIcon == NULL ? "" : cIcon)];
    
    if ([icon length] > 0)
        title = [title stringByAppendingFormat:@" %@", icon];
    
    BOOL active = NO;
    for (NSDictionary* item in self.selected) {
        NSNumber* pk = [item objectForKey:PIContextFieldNameKey];
        if ([pk intValue] == cId) {
            active = YES;
            break;
        }
    }
    
    NSDictionary* item = [NSDictionary dictionaryWithObjectsAndKeys:
                          title, FWDetailListViewFieldTitle,
                          [NSNumber numberWithBool:active], FWDetailListViewFieldSelected,
                          nil];
    
    return item;
}

@end
